#include <stdio.h>
#include <unistd.h>
#include "motor_control.h"
#include "ohos_init.h"
#include "cmsis_os2.h"


/**
*用于模拟药盒提醒,电机转动时表示提醒,睡眠时间表示吃药间隔
*/
// 全局变量定义
int g_motor_level = 0;  // 当前电机速度级别
int fan_sta = 0;        // 电机运行状态

// 驱动电机函数
int motor_speed(int speed) {
    if (speed < 0) {
        speed = 0;
    }

    int level = (speed > MAX_SPEED_LEVEL) ? MAX_SPEED_LEVEL : speed;

    if (speed == 0) {
        // 关闭电机
        if (IoTPwmStop(MOTOR_PWM_CHN) != IOT_SUCCESS) {
            printf("Failed to stop PWM\n");
            return -1;
        }
        fan_sta = 0;
    } else {
        if (IoTPwmStart(MOTOR_PWM_CHN, level, PWM_FREQ) != IOT_SUCCESS) {
            printf("Failed to start PWM\n");
            return -1;
        }
        fan_sta = 1;
    }

    g_motor_level = level;
    return 0;
}

// 电机初始化
int motor_init() {
    if (IoTGpioInit(MOTOR_GPIO_IDX) != IOT_SUCCESS) {
        printf("Failed to initialize GPIO\n");
        return -1;
    }

    if (IoTGpioSetFunc(MOTOR_GPIO_IDX, IOT_GPIO_FUNC_GPIO_2_PWM2_OUT) != IOT_SUCCESS) {
        printf("Failed to set GPIO function\n");
        return -1;
    }

    if (IoTGpioSetDir(MOTOR_GPIO_IDX, IOT_GPIO_DIR_OUT) != IOT_SUCCESS) {
        printf("Failed to set GPIO direction\n");
        return -1;
    }

    if (IoTPwmInit(MOTOR_PWM_CHN) != IOT_SUCCESS) {
        printf("Failed to initialize PWM\n");
        return -1;
    }

    return 0;
}

// 电机控制任务
void motor_control_task(void) {
    motor_init();
    osThreadAttr_t attr;
    attr.name = "motor_control_task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = 20;  // 设置任务优先级
    while (1) {
        // 停止电机
        motor_speed(0);
        usleep(MOTOR_OFF_TIME);  // 电机停止60秒
        // 启动电机()
        motor_speed(3);
        usleep(MOTOR_ON_TIME);  // 电机运行10秒

        
    }
}

APP_FEATURE_INIT(motor_control_task);